package net.flowas.genericcrud.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.flowas.genericcrud.CrudType;
import net.flowas.genericcrud.RepositoryService;
import net.flowas.genericcrud.dto.PageModdel;
import net.flowas.genericcrud.dto.QueryOption;

public class TopRepositoryService implements RepositoryService{
	private RequestDispatcher dispatcher;
	  
    public void setDispatcher(RequestDispatcher dispatcher) {
	  this.dispatcher = dispatcher;
    }
    
	@Override
	public Long count(QueryOption<Map<String, Object>> option, Class type) {
		return (Long) dispatcher.hangleRequest(type, CrudType.COUNT, option);
	}

	@Override
	public <T> List<T> findRang(QueryOption<Map<String, Object>> option, Class<T> type) {
		return (List<T>) dispatcher.hangleRequest(type, CrudType.QUERY, option);
	}

	@Override
	public Object saveOrUpdate(Object entity) {		
	    QueryOption option = new QueryOption();
	    option.setExample(entity);
	    return dispatcher.hangleRequest(entity.getClass(), CrudType.MERGE,option);
	}

	@Override
	public void remove(Class type, Object id) {
		dispatcher.singleItemProcess(type, (Long)id, CrudType.DELETE);
	}

	@Override
	public <T> T findById(Class<T> type, Object id) {
		return (T) dispatcher.singleItemProcess(type, (Long)id, CrudType.GET);
	}

	@Override
	public void detach(Object entity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Collection<Class<? extends Serializable>> getHandledTypes() {
		return null;//(Collection<Class<? extends Serializable>>)dispatcher.getTypeMaps().values();
	}

	@Override
	public <T> PageModdel<T> queryWithCount(QueryOption<Map<String, Object>> option, Class<T> type) {
		//return (PageModdel<T>) dispatcher.hangleRequest(type, CrudType.QUERY_COUNT, option);
		PageModdel<T> page = new PageModdel<>();	
		page.setTotal(count(option, type));
		page.setRows(findRang(option, type));
		page.setCurrentPage(option.getPagingOptions().getCurrentPage());
		page.setPageSize(option.getPagingOptions().getPageSize());
		return page;
	}	
}
